'''
Created on Apr 4, 2011

@author: mwarren1
'''

import os, time
import cPickle
from maildroplibs import DEBUGSTREAM, ENABLEDEBUG, SETTINGS_DIR
from wx.tools.dbg import Logger

debug = Logger('Counter')
debug.SetStream(DEBUGSTREAM)
debug(enable = ENABLEDEBUG)

def save():
    if Counter.instance is not None:
        Counter.instance.save()
    else:
        debug("NO COUNTER FOUND!!!")
        
def getItem(item):
    if Counter.instance is not None:
        return Counter.instance[item]
    else:
        debug("NO COUNTER FOUND!!!")
        
def setItem(item, value):
    if Counter.instance is not None:
        Counter.instance[item] = value
    else:
        debug("NO COUNTER FOUND!!!")

class Counter(object):
    '''
    classdocs
    '''
    instance = None
    DEFAULT_FILENAME = "sls220.mds"

    def __init__(self, filename = DEFAULT_FILENAME):
        '''
        Constructor
        '''
        
        self.COUNT = 0
        self.LIMIT = 10
        self.DATE = time.strftime("%m%d%Y")
        
        self.__lstamp = None
        
        self.filepath = os.path.join(SETTINGS_DIR, filename)
        
        if os.path.exists(self.filepath):
            debug("Loading settings from file: " + self.filepath)
            try:
                with open(self.filepath, 'rb') as file:
                    savedSettings = cPickle.load(file)
            except Exception as e:
                print e
                debug(str(e))
                return
            
            keysMatch = True
            for key in self.__dict__.keys():
                if key not in savedSettings.__dict__:
                    keysMatch = False
            for key in savedSettings.__dict__.keys():
                if key not in self.__dict__:
                    keysMatch = False

            if keysMatch:
                self.__dict__ = savedSettings.__dict__
                debug(str(self))
            else:
                debug("Keys do not match! Deleting Save Count File")
                os.remove(self.filepath)
        
        self.__class__.instance = self
                
    def __str__(self): return repr(self.__dict__)
    
    def __getitem__(self,key): return self.__dict__[key]
    
    def __setitem__(self, key, item): self.__dict__[key] = item
    
    def save(self):
        
        if not os.path.exists(SETTINGS_DIR):
            os.mkdir(SETTINGS_DIR)
                
        if self.filepath is None:
            self.filepath = os.path.join(SETTINGS_DIR, self.__class__.DEFAULT_FILENAME)
        
        with open(self.filepath, 'wb') as file:
            cPickle.dump(self, file, 2)
            
        try:
            debug("Count File saved to " + self.filepath)
        except:
            pass
        